package com.temp.controller.admin;

import com.temp.dto.CategoryDTO;
import com.temp.dto.SearchCategoryDTO;
import com.temp.entity.Category;
import com.temp.result.Result;
import com.temp.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


@RestController
@RequestMapping("/api/admin/category")
@Api(tags = "管理类别相关接口")
@Slf4j
@Validated
public class AdminCategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping("/query")
    @ApiOperation("管理员获取所有类别")
    @RequiresPermissions("admin:category:query")
    public Result getAllCategory(@RequestBody SearchCategoryDTO categoryDTO) {
        categoryDTO.formatParam();
        return Result.success(categoryService.findAllCategory(categoryDTO),"apiMsg.querySuccess");
    }

    @PostMapping("/updateOrSave")
    @ApiOperation("管理员保存或者更新类别")
    @RequiresPermissions("admin:category:updateOrSave")
    public Result updateOrSave(@Valid @RequestBody CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        boolean isSuccess = categoryService.saveOrUpdate(category);

        return isSuccess ? Result.success("apiMsg.optionSuccess") : Result.error("apiMsg.optionError");
    }

    @DeleteMapping("/delete")
    @ApiOperation("管理员删除类别")
    @RequiresPermissions("admin:category:delete")
    public Result delCategory(@RequestParam Long id) {
        boolean isSuccess = categoryService.removeById(id);

        return isSuccess ? Result.success("apiMsg.optionSuccess") : Result.error("apiMsg.optionError");
    }
}
